package com.example.coupon.service.impl;

import com.example.coupon.dao.CouponTemplateDao;
import com.example.coupon.entity.CouponTemplate;
import com.example.coupon.exception.CouponException;
import com.example.coupon.service.IAsyncService;
import com.example.coupon.service.IBuildTemplateService;
import com.example.coupon.vo.TemplateRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 构建优惠券模版接口实现
 * @author wangbo
 * @description:
 * @date 2021/2/1814:15
 */
@Slf4j
@Service
public class BuildTemplateServiceImpl implements IBuildTemplateService {

    @Resource
    private IAsyncService asyncService;

    @Resource
    private CouponTemplateDao couponTemplateDao;

    /**
     * 创建优惠券模版
     * @param request {@link TemplateRequest} 模版信息请求对象
     * @return
     * @throws CouponException
     */
    @Override
    public CouponTemplate buildTemplate(TemplateRequest request) throws CouponException {

        //参数合法性校验
        if(!request.validate()){
            throw new CouponException("BuildTemplate Param Is Not Valid");
        }
        //判断同名的优惠券模版是否存在
        if (null != couponTemplateDao.findByName(request.getName())){
            throw new CouponException("Exist Same Name Template!");
        }

        //构造CouponTemplate 并保存到数据库中
        CouponTemplate template = requestToTemplate(request);
        template = couponTemplateDao.save(template);

        //根据优惠券模版异步生成优惠券码
        asyncService.asyncConstructCouponByTemplate(template);
        return template;
    }

    /**
     * 将TemplateRequest 转换为 CouponTemplate
     * @param request
     * @return
     */
    private CouponTemplate requestToTemplate(TemplateRequest request){
        return new CouponTemplate(request.getName(),
                request.getLogo(),
                request.getDesc(),
                request.getCategory(),
                request.getProductLine(),
                request.getCount(),
                request.getUserId(),
                request.getTarget(),
                request.getRule());
    }
}
